<?php


class ErrorHandler
{

    protected $exceptions = [
        E_ERROR => "E_ERROR",
        E_WARNING => "E_WARNING",
        E_PARSE => "E_PARSE",
        E_NOTICE => "E_NOTICE",
        E_CORE_ERROR => "E_CORE_ERROR",
        E_CORE_WARNING => "E_CORE_WARNING",
        E_COMPILE_ERROR => "E_COMPILE_ERROR",
        E_COMPILE_WARNING => "E_COMPILE_WARNING",
        E_USER_ERROR => "E_USER_ERROR",
        E_USER_WARNING => "E_USER_WARNING",
        E_USER_NOTICE => "E_USER_NOTICE",
        E_STRICT => "E_STRICT",
        E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR",
        E_DEPRECATED => "E_DEPRECATED",
        E_USER_DEPRECATED => "E_USER_DEPRECATED",
        E_ALL => "E_ALL"
    ];

    protected $debug = false;


    public function __construct($debug = true)
    {
        $this->debug = $debug;
    }

    public function bootstrap()
    {
        // 禁用默认的错误处理函数
        error_reporting(0);
        // 设置自定义错误处理函数
        set_error_handler([$this, 'handle'], E_ALL | E_STRICT);
    }

    public function handle($errno, $errmsg, $file, $line)
    {
        // 错误发生的时间
        $dt = date("Y-m-d H:i:s (T)");

        $msg = $errmsg . "($errno)" . $file . " ($line).";
        switch ($errno) {
            case E_NOTICE:
                if ($this->debug) {
                    return 'notice' . $msg;
                } else {
                    // 记录日志
                    return 'log';
                }
                break;
            default:
                if ($this->debug) {
                    return 'error' . $msg;
                } else {
                    // 记录错误日志到文件
                    $log_file = 'logs/' . date('Y_m_d') . '.log';
                    error_log(date("[ c ]") . $msg . PHP_EOL, 3, $log_file, null);
                }
                break;
        }
    }

}

// 自定义错误处理
(new ErrorHandler())->bootstrap();


class UserErrorException extends Exception
{

    public function __toString()
    {
        return $this->getFile() . $this->getCode() . $this->getLine() . $this->getMessage();
    }

}

// try {
//     throw new UserErrorException('继承默认异常', 403);
// } catch (UserErrorException $exception) {
//     echo $exception->getMessage() . $exception->getCode();
// }


class ErrorExceptionHandler
{
    public function init()
    {
        set_exception_handler([$this, 'exception']);
    }

    public function exception($e)
    {
        if (method_exists($e, 'render')) {
            $e->render();
        } else {
            die($e);
        }
    }
}

(new ErrorExceptionHandler())->init();

throw new Exception('自定义异常', 404);





